package com.itheima.reggie.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.CacheRequest;
import java.security.SecureRandom;
import java.util.*;

/*
* 沙箱支付!!!
*
* */
@RestController
public class PayController {
    //应用的APPID
    private final String APP_ID = "2021000121670503";
    //生成的应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCVUuidUJjZjj9LJxE6vKu84b+X/4xpZZQ8hHxP6kVSfqzGPTUWQfp4RnXCgeszNjEO96L31zRVVL7Z4opmJr7D7kGLaMOfB1zJAGWerJNR+dTMCVEKfuEebsJYspt6+wXcQ8pXmt7m8bqWp1fNW76CT5A2sS4NZVEN1nKwDlMiUswyXsA+XivXJ/xI5zTz7AfiFGAtWVFrUYNBwD8LqI7TS4L+5rouuuGv3NiIpaswOcBpM1hVM/q4ZJuzO171Hf4BSMLfRcv9sr0aHbqwGmD9mo8EpEKIF9VWwwRrVFz/DB/0eHIHNMgN1pggI7axLKR6G3lRXTOh47RXGZjUkLh7AgMBAAECggEAKIpu7y8PoJlXI89ChUDuG4Tq4JiYBZF3koqhuYywL3qG6/d4L0fQedEfbaSaN7gxz496JnG+GqC8hClWS++fAVDxaKkT21xDW6sI6/CMusfqd07cOs5BzmJhz3UGc3gtmiSpjelVNTxR3U8nrnCHI5f4XnDyQN7OB8S+NIBfH8UPzqNhRrprM42eIB0IU6Wdb3AlNSndMwrFqoRD/HSlQCHKQ58YKMt8DFp5gXqRMxT1kSkRKreBL+5nw+hm/oWZmSn1oxQSTQT6tSS1Sn9tLWYzKoHqJlMqnoL1W0TkN/IKBHMX1+HDygIf4Z9XExIlgKSfdcdL2VHsyoauZIvuqQKBgQD4BBL0hjdmMU2W84ObqNuKwV/dq36oOKM+MIbjZ7926cpLFpJO1NGcy0aVfKjXVWYAXFLJyyX2f2uVor451AHFKI3EDo+p1ePflwJj5mGth4ZnqbsFk3Nm9UEJ5emC419YIvC2MO6aQODOjAVSBvye+BbEeyd45uxUqzCSoxmo/QKBgQCaIYCzVKaQgAt9wNku1+gAK4QsGtKrqNyPJTH0mYcldEJLnNx470255VeMS5DS6QaHhPZHCR35S8iG9YnOvy3cEFhe5Uo/x0bvNQwyabdwiEJjOfn9hFPYuZEAUO100jjcCl/VHdRn5r57lixIHRz6dg93hmtX4Mt1/qWiKrK81wKBgQCTVyhDqHDE/0lPAkAPe5NhrVvcfwNxwKQKUB3yfzIZ3O5XCYPF3Vzhv0mhiTttIcjFMhPk2hEljbFGZjaIeFDM5jjCXrwuc2k67aV33+frhXXto8H9oAmRAuaukK3XGmkMHUXPluZJMX3cdwa6Inh1oIE2HMvoYZfI/SKQGuElqQKBgQCBOaOxN0DrmB+KUL0GtEi0k8eePuLwv4QklBfdLzeLJH1M7fg/gMvXFz0eyGBlJLCvwL/HcRJraKl41baz28A0aJPfBDkLXiXP+tb+EXqWY/fdP8ekUWUHKRY0gKWGM5cujZgpk3f5oRGFhrQbxiT8rS1slgu7wyJzDIyMeWYgQwKBgQDwbABxwMixRgmCewmy8TrqUx9K9EbOinIs0yumW4W+ukyT07AJDtdNTbkUzqlLQNg/2SbDfU6DxfvioDWCvgbfXwy3kxDhIRPN6Qku0rZcBJCaydqIFGrlJI/xq8rMi4D3vQfddAhWLfkeZ6zA8JnO8+W8eQ5lraRzH63+NeGL2Q==";
    private final String CHARSET = "UTF-8";
    //支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAttt6v0TaIYz3uRrffQis6u+88mAb6rnUaBfCbVrnzM8PUWDvbhvIKBYEqWxl7nT+td3NL+xdjSljO2yxE5H8Jo+rUL9ZjQSaud7INpL5Giw313K/cL/XD02LyZ4QgW/DsNGwj5X76VyDVPsR6FtLxgJCdIfQeNJ8/wF69I03h2xw2FTWQTk1Kq+0G8pieajrcthfqCpelFUG6SlqAm/QBP9+f94FW/6pAJ9LHU83Dn+UcoVvAydtI+UPCEIw8rxKdG8JOM/OLSeyAP7xKvLgzG6Mq2BlYANRTVHt2emQZOQ1qHgn5RFji/9cMJZUsteo9flmZG/U5syLTrNY+eiNHwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/backend/page/login/login.html";


//    @RequestMapping("/alipay")
    @GetMapping("/alipay")
//    @PostMapping("/alipay")  支付宝沙箱支付同步调用 不是post请求,是get请求
   public void alipay(HttpServletResponse httpResponse) throws IOException {

       Random r=new Random();
       //实例化客户端,填入所需参数
       AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
       AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
       //在公共参数中设置回跳和通知地址
       request.setReturnUrl(RETURN_URL);
       request.setNotifyUrl(NOTIFY_URL);

       //商户订单号，商户网站订单系统中唯一订单号，必填
       //生成随机Id
       String out_trade_no = UUID.randomUUID().toString();
       //付款金额，必填
       String total_amount =Integer.toString(r.nextInt(1)+1);
       //订单名称，必填
       String subject ="奥迪RS7 2022款 A8L 60 TFSl quattro豪华型";
       //商品描述，可空
       String body = "尊敬的会员欢迎购买奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
       request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
               + "\"total_amount\":\""+ total_amount +"\","
               + "\"subject\":\""+ subject +"\","
               + "\"body\":\""+ body +"\","
               + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
       String form = "";
       try {
           form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
       } catch (AlipayApiException e) {
           e.printStackTrace();
       }
       httpResponse.setContentType("text/html;charset=" + CHARSET);
       httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
       httpResponse.getWriter().flush();
       httpResponse.getWriter().close();
   }

//    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    @GetMapping( "/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
//            payService.updateById(Integer.valueOf(out_trade_no));
            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }

    }
}

